package JUC.lock锁;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author CKC
 * @DateTime 2021/3/11 8:48
 * <p>
 * <p>
 * 题目：三个售货员    卖出    30张票
 * <p>
 * <p>
 * 1 在高内聚低耦合的前提下，线程    操作     资源类
 * <p>
 * 1.1
 */
public class SaleTicketDemo01 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {
            for (int i = 1; i <= 50; i++) ticket.sale();
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i <= 40; i++) ticket.sale();
        }, "Son").start();
        new Thread(() -> {
            for (int i = 1; i <= 40; i++) ticket.sale();
        }, "C").start();
    }
}


class Ticket {
    //资源类==实例变量+ 实例方法
    //    List list = new ArrayList();
    Lock lock = new ReentrantLock();
    private int number = 120;

    public /*synchronized*/ void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "\t卖出第：" + (number--) + "\t还剩" + number + "张票");
            } else {
                System.out.println(Thread.currentThread().getName() + "票已经买光了");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
